package com.aiit.controller.admin;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;

@Controller
@RequestMapping("/login")
@Slf4j
public class VerificationController {

    /**
     * 生成图形验证码
     */
    @RequestMapping("/code")
    public void createCode(HttpServletResponse response, HttpServletRequest request) {

        try {
            BufferedImage image = new BufferedImage(100, 40, BufferedImage.TYPE_BYTE_GRAY);

            Graphics g = image.getGraphics();
            g.setColor(Color.yellow);
            g.fillRect(0, 0, 120, 60);

            g.setColor(Color.green);
            g.drawLine(10, 20, 70, 40);
            Random random = new Random();
            for (int i = 0; i < 10; i++) {
                int x1 = random.nextInt(100);
                int y1 = random.nextInt(40);
                int x2 = random.nextInt(100);
                int y2 = random.nextInt(40);
                g.drawLine(x1, y1, x2, y2);
            }

            g.setColor(Color.magenta);
            Font font = new Font("Arial", Font.PLAIN, 24);
            g.setFont(font);
            int x = 20;
            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < 4; i++) {
                int num = random.nextInt(10);
                sb.append(num);
                g.drawString(String.valueOf(num), x, 20);
                x = x + 20;
            }

            ServletOutputStream out = response.getOutputStream();

            HttpSession session = request.getSession();

            // 将验证码字符串存储到会话中
            session.setAttribute("verificationCode", sb.toString());
            session.setMaxInactiveInterval(60 * 5); // 设置会话超时时间为5分钟

            log.info("生成的session的id是: {}", session);
            ImageIO.write(image, "gif", out);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
